const timesToYyMmDd = (times)=>{//时间格式转换
	if(!times) return
  var d = new Date(times);
  var oTime= d.getFullYear() +
  '-' + (d.getMonth() + 1 >= 10 ?  d.getMonth() + 1 : '0' + (d.getMonth() + 1) ) +
  '-' + (d.getDate() >=10 ? d.getDate() : '0' + d.getDate() ) +
  ' ' + (d.getHours() >=10 ? d.getHours() : '0' + d.getHours()) +
  ':' + (d.getMinutes() >=10 ? d.getMinutes() : '0' + d.getMinutes()) +
  ':' + (d.getSeconds() >=10 ? d.getSeconds() : '0' + d.getSeconds() );
  return oTime
}

//转换成时间戳
const YyMmDdToTimes = (time) => {
	if(!time && time != 0) return ''
  return new Date(time.replace(/-/g, '/')).getTime()
}


const timesToYyMmDd1 = (times,geshi = 'YY-MM-DD HH:MM:SS')=>{//时间转换
	if(!times) return ''
  var d = new Date(times);
	let oTime = ''
	switch(geshi){
		case 'YY':
			oTime = d.getFullYear()
			break;
		case 'MM':
			oTime = d.getMonth() + 1
			break;
		case 'DD':
			oTime = d.getDate()
			break;
		case 'YY-MM':
			oTime = d.getFullYear() +
			'-' + (d.getMonth() + 1 >= 10 ?  d.getMonth() + 1 : '0' + (d.getMonth() + 1) )
			break;
		case 'YY-MM-DD':
			oTime = d.getFullYear() +
			'-' + (d.getMonth() + 1 >= 10 ?  d.getMonth() + 1 : '0' + (d.getMonth() + 1) ) +
			'-' + (d.getDate() >=10 ? d.getDate() : '0' + d.getDate() )
			break;
		case 'HH:MM:SS':
			oTime= (d.getHours() >=10 ? d.getHours() : '0' + d.getHours()) +
			':' + (d.getMinutes() >=10 ? d.getMinutes() : '0' + d.getMinutes()) +
			':' + (d.getSeconds() >=10 ? d.getSeconds() : '0' + d.getSeconds() );
			break;
		case 'YY-MM-DD HH:MM:SS':
			oTime= d.getFullYear() +
			'-' + (d.getMonth() + 1 >= 10 ?  d.getMonth() + 1 : '0' + (d.getMonth() + 1) ) +
			'-' + (d.getDate() >=10 ? d.getDate() : '0' + d.getDate() ) +
			' ' + (d.getHours() >=10 ? d.getHours() : '0' + d.getHours()) +
			':' + (d.getMinutes() >=10 ? d.getMinutes() : '0' + d.getMinutes()) +
			':' + (d.getSeconds() >=10 ? d.getSeconds() : '0' + d.getSeconds() );
			break;
	}
  return oTime
}

const formatTime = (timestamp) => {
  let time = new Date(timestamp)
  let stTime = timestamp - time.getHours() * 60 * 60 * 1000 - time.getMinutes() * 60 * 1000 - time.getSeconds() * 1000 - time.getMilliseconds();
  return stTime
}

// 0：00-23：59
//筛选条件开始时间和结束时间
const getEndStartTime = (dateRange) => {
  let startTime = dateRange[0]
  let startTime1 = YyMmDdToTimes(startTime)
  let startTime2 = formatTime(startTime1)
  let startTime3 = timesToYyMmDd1( startTime2 )
   let endTime = dateRange[1]
   let endTime1 = YyMmDdToTimes(endTime)
   let endTime2 = formatTime(endTime1)
  let endTime3 = endTime2 + 24 * 60 * 60 * 1000 - 1
  let endTime4 = timesToYyMmDd1( endTime3 )
  return {
    startTime3,endTime4
  }
}

  //格式化数字
	const formatNumberDate = (n) => {
		n = n.toString()
		return n[1] ? n : '0' + n
	}

	//获取某月的天数
const getMonthDays = (year, myMonth) => {
	let monthStartDate = new Date(year, myMonth - 1, 1)
	let monthEndDate = new Date(year, myMonth, 1)
	let days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24)
	return days
}

//格式化日期
const formatDate = (date) => {
	let myyear = date.getFullYear()
	let mymonth = date.getMonth() + 1
	let myweekday = date.getDate()
	return [myyear, mymonth, myweekday].map(formatNumberDate).join('-')
}

//获取本月的开始日期
const getMonthStartDate = (year, month) => {
  console.log('dddddddddddd', year, month)
    return formatDate(new Date(year, month - 1, 1))
}
//获取本月的结束日期
const getMonthEndDate = (year, month) => {
	return formatDate(new Date(year, month - 1, getMonthDays(year, month)));
}

/**
 * 根居时间字符串计算时间差，
 * @param startTime 2020-09-15 15:53:04 开始时间
 * @param endTime 2020-09-15 15:53:04 结束时间
 * @returns {*} {
 *  d:天，
 *  h:小时，
 *  min：分钟
 *  s:秒
 *  ms：毫秒
 * }
 */
const getTimeDifference = ( startTime, endTime) => {
  let timeData={}
  if(startTime != null  ){
    let sd = startTime.substring(0, 19).replace(/-/g, '/')// 将时间字符串截取到秒，并将其中的-换成/
    let se = '' // 这是定义结束时间，如果为空，就获取当前时间
    let cdate = new Date()
    if( endTime != null  || endTime != ''){
      se = endTime.substring(0, 19).replace(/-/g, '/')// 将时间字符串截取到秒，并将其中的-换成/
    }else {
      se = cdate.getTime()
    }
    let sde = new Date(se).getTime()  - new Date(sd).getTime()  // 将时间字符转成时间戳
    if(sde > 1){  // 当有差值时，就计算
      let a = (sde/1000 + '').split('.') // 这是获取ms
      if(a.length>1){   
        timeData['ms'] = Math.floor(Number('0.'+a[1]*1000))
      }
      let b = (sde/1000/60 +'').split('.')  // 这是获取s
      if(b.length>1){
        timeData['s'] = Math.floor(Number('0.'+b[1])*60)
      }
      let c = (sde/1000/60/60 +'').split('.')   // 这是获取min
      if(c.length>1){
        timeData['min'] = Math.floor(Number('0.'+c[1])*60)
      }
      let d =(sde/1000/60/60/24 +'').split('.') // 这是获取h
      if(d.length>1){
        timeData['h'] = Math.floor(Number('0.'+d[1])*24)
      }
      timeData['d'] = Number(d[0])  // 这是获取d
    }
  }
	let str = ( timeData['d'] > 0 ? timeData['d'] + '天' : '' ) + ( timeData['h'] > 0 ? timeData['h'] + '小时' : '' ) + 
	( timeData['min'] > 0 ? timeData['min'] + '分钟' : '' ) + ( timeData['s'] > 0 ? timeData['s'] + '秒' : '' )
  return str;
}

/**
 * 获取当前日期几天后的数据或者指定日期30天后数据
 * @param day 天数
 */
 const getDay = (day,time,isTime) => {
  var today = time ? new Date(time) : new Date();
  var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
  today.setTime(targetday_milliseconds); //注意，这行是关键代码
  
  var tYear = today.getFullYear();
  var tMonth = today.getMonth();
  var tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  let strs = tYear + "-" + tMonth + "-" + tDate;
  let tHour = today.getHours()
  let tMinutes = today.getMinutes()
  let tSeconds = today.getSeconds()
  tHour = doHandleMonth(tHour);
  tMinutes = doHandleMonth(tMinutes);
  tSeconds = doHandleMonth(tSeconds);
  if(isTime) strs = strs + ' ' + tHour + ':' + tMinutes + ':' + tSeconds
  return strs
}

 const doHandleMonth = (month) => {
  var m = month;
  if (month.toString().length == 1) {
     m = "0" + month;
   }
    return m;
  }

  //获取上一个的日期返回YY-MM-DD
const getlastMonth = () => {
    let now = new Date();
    // 当前月的日期
    let nowDate = now.getDate();
    let lastMonth = new Date(now.getTime());
    // 设置上一个月（这里不需要减1）
    lastMonth.setMonth(lastMonth.getMonth());
    // 设置为0，默认为当前月的最后一天
    lastMonth.setDate(0);
    // 上一个月的天数
    let daysOflastMonth = lastMonth.getDate();
    // 设置上一个月的日期，如果当前月的日期大于上个月的总天数，则为最后一天 
    lastMonth.setDate(nowDate > daysOflastMonth ? daysOflastMonth : nowDate);
    return timesToYyMmDd1(lastMonth,'YY-MM-DD');
}

//获取指定日期前多个月或者后多个月日期
//格式返回YY-MM-DD
const gettoLastMonth = (date = '',num = 0) =>{
  var today = date ? new Date(date) : new Date()
  var lastMonth = new Date(today.getFullYear(), today.getMonth() + num, today.getDate());
  var year = lastMonth.getFullYear();
  var month = lastMonth.getMonth() + 1;
  month = month < 10 ? "0" + month : month;
  var day = lastMonth.getDate();
  day = day < 10 ? "0" + day : day;
  var lastMonthTime = year + "-" + month + "-" + day;
  return lastMonthTime
}

const getEveryDay = (date1,date2,format) => {
  let dates = []
  let [startDate,endDate] = new Date(date1) < new Date(date2)? [new Date(date1),new Date(date2)] : [new Date(date2),new Date(date1)]
     while(startDate <= endDate) {
      dates.push(new Date(startDate))
      startDate.setDate(startDate.getDate() + 1)
     }
     dates = dates.map(item => {
          item = item.toLocaleDateString().split('/').map(items => {
              items = items.padStart(2,'0')
              return items
          }).join(format || '-')
          return item
     })
     return dates
}
 

export  {
  timesToYyMmDd,timesToYyMmDd1,YyMmDdToTimes,formatTime,getEndStartTime,getMonthDays,
	getMonthStartDate,getMonthEndDate,getTimeDifference,getDay,getlastMonth,gettoLastMonth,getEveryDay,
}
